/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.qb9.flashlib.profiling
{
	import flash.utils.getTimer;
	
	/**
	 * Runs functions many times and saves the elapsed time
	 */
	
	public class Benchmarker
	{
		protected var net:Boolean;
		
		/**
		 * Creates a new Benchmarker instance
		 * @param net If true, the Benchmarker deducts the iteration+function call time (could yield negative values).
		 */
		public function Benchmarker(net:Boolean=false)
		{
			this.net = net;
		}
		
		protected function _run(fn:Function, times:uint) : uint
		{
			var start:int = getTimer();
			
			while (times--)
				fn();
				
			return getTimer() - start;
		}
		
		/** Run one function many times and get the elapsed time */
		public function run(fn:Function, times:uint = 1000) : int
		{
			var time:int = _run(fn,times);
			
			if (net)
				time -= _run(empty,times);
				
			return time; 
		}
		
		/** Run one function many times and repeat the process saving all the elapsed times */
		public function runMany(fn:Function, times:uint = 1000, repeat:uint = 10) : Array
		{
			var arr:Array = new Array(repeat);
			
			while (repeat--)
				arr[repeat] = run(fn,times);
				
			return arr;
		}
		
		private function empty() : void
		{
		}

	}
}